import { ref, onMounted, onUnmounted } from "vue";
import { mainAct } from "@/store/activeda";
/**
 * @description 用于判断设备类型的自定义 Hook
 * @returns {isMobile, isTablet, isDesktop} 返回一个包含设备类型的对象
 * @author rio
 * @date 2024.12.30
 */
const useDeviceType = () => {
  const isMobile = ref(false);
  const isTablet = ref(false);
  const isDesktop = ref(false);
  const main = mainAct();
  // 判断平台类型（iOS, Android, Windows 等）
  const detectPlatform = () => {
    const userAgent = navigator.userAgent;
    if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
      return "iOS";
    }
    if (/Android/.test(userAgent)) {
      return "Android";
    }
    if (/Windows/.test(userAgent)) {
      return "Windows";
    }
    return "Unknown";
  };

  // 根据平台设置初步的设备类型
  const detectDeviceByPlatform = () => {
    const platform = detectPlatform();
    if (platform === "iOS" || platform === "Android") {
      isMobile.value = true;
    } else if (platform === "Windows") {
      isDesktop.value = true;
    } else {
      isTablet.value = true; // 默认处理为平板
    }
  };

  // 根据屏幕宽度动态判断设备类型
  const updateDeviceTypeByWidth = () => {
    const width = window.innerWidth;
    if (width < 768) {
      isMobile.value = true; // 手机
      isTablet.value = false;
      isDesktop.value = false;
      main._isMobile = true;
      main._isTablet = false;
      main._isDesktop = false;
    } else if (width >= 768 && width <= 1024) {
      isTablet.value = true; // 平板
      isMobile.value = false;
      isDesktop.value = false;
      main._isTablet = true;
      main._isMobile = false;
      main._isDesktop = false;
    } else {
      isDesktop.value = true; // PC
      isMobile.value = false;
      isTablet.value = false;
      main._isDesktop = true;
      main._isMobile = false;
      main._isTablet = false;
    }
    if (main.isApp) {
      main._isMobile = true;
      main._isTablet = false;
      main._isDesktop = false;
    }
  };

  // 结合平台和宽度来判断设备类型
  const detectDevice = () => {
    detectDeviceByPlatform(); // 首先根据平台进行初步判断
    updateDeviceTypeByWidth(); // 然后根据宽度来调整设备类型
  };

  // 在组件挂载时更新设备类型
  onMounted(() => {
    detectDevice();
    window.addEventListener("resize", updateDeviceTypeByWidth);
  });

  // 在组件卸载时移除事件监听
  onUnmounted(() => {
    window.removeEventListener("resize", updateDeviceTypeByWidth);
  });

  return {
    isMobile,
    isTablet,
    isDesktop
  };
};

export { useDeviceType };
